document.addEventListener("deviceready", onDeviceReady, false);
var db
function onDeviceReady() {
    db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
    db.transaction(populateDB, errorCB, successCB);
    if (localStorage.getItem('rememberAccount') == "1") {
        //alert('You are loggedin');
    }else{
    	$.mobile.changePage("lo_reg.html", {
			transition : 'slideup'
		});
    }
}
//Create tables being used by app
function populateDB(tx) {
     tx.executeSql('CREATE TABLE IF NOT EXISTS USERS (id unique,name,photo,email,token)');
}

function errorCB(err) {
    alert("Error processing SQL: "+err.code);
}

function successCB() {
    //alert("success!");
}


function createUser(){
	db.transaction(createuserDB, errorCB, successCB);
}

function createuserDB(tx){
	var name = $("#rusername").val();
	var photo = 'imrankhan';
	var email = 'imrankhan@gmail.com';
	var token = '89hh87yh8ggyufrd7stfxchkhpn768r7';
	tx.executeSql('SELECT * FROM USERS WHERE name = "'+name+'"',[],findquerySuccess, errorCB);
	//tx.executeSql('INSERT INTO USERS(name,photo,email,token) VALUES("'+name+'","'+photo+'","'+email+'","'+token+'")');
}

function findquerySuccess(tx, results) {
    var len = results.rows.length;
	if(len==0){
		var name = $("#rusername").val();
		var email = $("#remail").val();;
		var token = '89hh87yh8ggyufrd7stfxchkhpn768r7';
		tx.executeSql('INSERT INTO USERS(name,photo,email,token) VALUES("'+name+'","'+photo+'","'+email+'","'+token+'")');
	}else{
		localStorage.setItem('rememberAccount',1);
		$.mobile.changePage("index.html#menu", {
			transition : 'slideup'
		});
	}
	//readTable();
}

function readTable(){
	db.transaction(queryDB,errorCB, successCB);
}

function queryDB(tx) {
    tx.executeSql('SELECT * FROM USERS', [], querySuccess, errorCB);
}


function querySuccess(tx, results) {
    var len = results.rows.length;
    console.log("DEMO table: " + len + " rows found.");
    for (var i=0; i<len; i++){
        console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data =  " + results.rows.item(i).data);
        
    }
}

function logout(){
	localStorage.setItem('rememberAccount',0);
	$.mobile.changePage("lo_reg.html", {
			transition : 'slideup'
	});
}

